package com.qumoyugo.springframework.core.convert.support;

import com.qumoyugo.springframework.beans.BeansException;
import com.qumoyugo.springframework.beans.factory.FactoryBean;
import com.qumoyugo.springframework.beans.factory.InitlializingBean;
import com.qumoyugo.springframework.core.convert.ConversionService;
import com.qumoyugo.springframework.core.convert.converter.Converter;
import com.qumoyugo.springframework.core.convert.converter.ConverterFactory;
import com.qumoyugo.springframework.core.convert.converter.ConverterRegistry;
import com.qumoyugo.springframework.core.convert.converter.GenericConverter;

import java.util.Set;

/**
 * @author Cedric
 * @date 2021/12/09 16:03
 * @description 创建类型转换工厂
 */
public class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitlializingBean {

    private Set<?> converters;

    private GenericConversionService conversionService;

    @Override
    public ConversionService getObject() throws BeansException {
        return conversionService;
    }

    @Override
    public Class<?> getObjectType() {
        return conversionService.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws BeansException {
        conversionService = new DefaultConversionService();
        registerConverters(converters, conversionService);
    }

    private void registerConverters(Set<?> converters, ConverterRegistry registry) {
        if (converters != null) {
            for (Object converter : converters) {
                if (converter instanceof GenericConverter) {
                    registry.addConverter((Converter<?, ?>) converter);
                } else if (converter instanceof Converter) {
                    registry.addConverter((Converter<?, ?>) converter);
                } else if (converter instanceof ConverterFactory) {
                    registry.addConverterFactory((ConverterFactory<?, ?>) converter);
                } else {
                    throw new BeansException("Each converter object must implements one of the GenericConverter, Converter, or ConverterFactory interfaces");
                }
            }
        }
    }

    public Set<?> getConverters() {
        return converters;
    }
}
